﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DFGK_WMS.Repository
{
    public class TMaterialCategoryRepository : BaseRepository<TMaterialCategory>, ITMaterialCategoryRepository
    {
        public TMaterialCategoryRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }

        /// <summary>
        /// 添加物料分类
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddTMaterialCategory(TMaterialCategory m, out string message)
        {
            message = "";
            var obj = Context.TMaterialCategories.AsNoTracking().FirstOrDefault(x => x.Code == m.Code);
            if (obj != null)
            {
                message = "编码已存在！";
                return false;
            }        
            m.CreateDate = DateTime.Now;
            Context.Add(m);
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 列表显示
        /// </summary>
        /// <param name="mname"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<MenuDto> GetMaterialCategortList(string mname, int pageIndex, int pageSize, out int totalCount)
        {
            var mlist = Context.TMaterialCategories.AsQueryable();
            if (!string.IsNullOrEmpty(mname))
            {
                mlist = mlist.Where(x => x.Name.Contains(mname));
            }

            if(mlist.Any())
            {
                mlist = mlist.OrderBy(x => x.ParentId);
                var mmlist = mlist.FirstOrDefault();
                var list2 = GetMenuLists(mlist.ToList(), mmlist.ParentId.GetValueOrDefault());
                totalCount = list2.Count();
                list2 = list2.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                return list2;
            }
            
            var list = GetMenuLists(mlist.ToList(), 0);
            totalCount = list.Count();
            list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return list;
        }

        /// <summary>
        /// 递归显示分类列表
        /// </summary>
        /// <param name="list"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public static List<MenuDto> GetMenuLists(List<TMaterialCategory> list, int pid)
        {
            try
            {
                return list.Where(x => x.ParentId == pid).Select(x => new MenuDto
                {
                    id = x.Id,
                    ParentId = x.ParentId,
                    CreateUserName = x.CreateUserName,
                    UpdateUserName = x.UpdateUserName,
                    UpdateDate = x.UpdateDate,
                    CreateDate=x.CreateDate,
                    Meta = new MetaDto
                    {
                        MenuName = x.Name,
                        MenuIcon=x.Code,
                    },
                    DisplayOrder = x.DisplayOrder,
                    children = GetMenuLists(list, x.Id)
                }).OrderBy(x => x.DisplayOrder).ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DelTMaterialCategory(int mid)
        {
            var obj = Context.TMaterialCategories.Find(mid);
            if(obj!=null)
            {                
                Context.TMaterialCategories.Remove(obj);
                var objparentidlist = Context.TMaterialCategories.AsNoTracking().Where(x => x.ParentId == mid);
                if(objparentidlist.Any())
                    Context.TMaterialCategories.RemoveRange(objparentidlist);
            }
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public TMaterialCategory GetTMaterialCategoryById(int mid)
        {
            return Context.TMaterialCategories.Find(mid);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdTMaterialCategory(TMaterialCategory m, out string message)
        {
            message = "";
            var list = Context.TMaterialCategories.AsNoTracking().FirstOrDefault(x => x.Id != m.Id && x.Code == m.Code);

            if (list != null)
            {
                message = "编码已存在！";
                return false;
            }         
            m.UpdateDate = DateTime.Now;
            Context.TMaterialCategories.Update(m);
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 添加-树形显示
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Menuitem> GetMaterialCateMenuitemList()
        {
            var list = Context.TMaterialCategories.AsNoTracking().AsQueryable();

            return GetMaterialCateMenuitemList(list.ToList(), 0);
        }

        public static List<Menuitem> GetMaterialCateMenuitemList(List<TMaterialCategory> list,int? pid)
        {
            return list.Where(x => x.ParentId == pid).Select(x=> new Menuitem
            {
                value=x.Id,
                label=x.Name,
                children= GetMaterialCateMenuitemList(list,x.Id).Count>0? GetMaterialCateMenuitemList(list,x.Id):null
            }).ToList();
        }
    }
}
